package com.games.portal.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;

import com.games.portal.processor.GameProcessor;
import com.games.portal.processor.GameProcessorCallback;

/**
 * Intent service to execute a GET HTTP REST
 * @author hirsche
 *
 */
public class Html5Service extends IntentService{

	public static final String METHOD_EXTRA = "METHOD_EXTRA";
	public static final String METHOD_GET = "GET";
	public static final String RESOURCE_TYPE_EXTRA = "RESOURCE_TYPE_EXTRA";
	public static final int RESOURCE_TYPE_GAMES = 1;
	public static final String SERVICE_CALLBACK = "SERVICE_CALLBACK";
	public static final String ORIGINAL_INTENT_EXTRA = "ORIGINAL_INTENT_EXTRA";
	private static final int REQUEST_INVALID = -1;
	private ResultReceiver callBack;
	private Intent mOriginalRequestIntent;

	public Html5Service() {
		super("Html5Service");
	}

	@Override
	protected void onHandleIntent(Intent requestIntent) {

		mOriginalRequestIntent = requestIntent;

		// Get request data from Intent
		String method = requestIntent.getStringExtra(Html5Service.METHOD_EXTRA);
		int resourceType = requestIntent.getIntExtra(Html5Service.RESOURCE_TYPE_EXTRA, -1);
		callBack = requestIntent.getParcelableExtra(Html5Service.SERVICE_CALLBACK);

		switch (resourceType) {
		case RESOURCE_TYPE_GAMES:

			if (method.equalsIgnoreCase(METHOD_GET)) {
				GameProcessor processor = new GameProcessor(getApplicationContext());
				processor.getGameList(makeGameProcessorCallback());
			} else {
				callBack.send(REQUEST_INVALID, getOriginalIntentBundle());
			}
			break;

			
		default:
			callBack.send(REQUEST_INVALID, getOriginalIntentBundle());
			break;
		}

	}

	private GameProcessorCallback makeGameProcessorCallback() {
		GameProcessorCallback callback = new GameProcessorCallback() {

			@Override
			public void send(int resultCode) {
				if (callBack != null) {
					callBack.send(resultCode, getOriginalIntentBundle());
				}
			}
		};
		return callback;
	}
	
	protected Bundle getOriginalIntentBundle() {
		Bundle originalRequest = new Bundle();
		originalRequest.putParcelable(ORIGINAL_INTENT_EXTRA, mOriginalRequestIntent);
		return originalRequest;
	}

}
